<template>
  <article class="image-captcha">
    <el-dialog v-model="showCaptcha">
      <BaseCard
        v-model:formData="formData"
        v-bind="{ formRules, tiplinkText, cardShadow }"
        @submit="submitCaptcha"
        @tipClick="showCaptcha = false"
        class="image-captcha-card"
      >
        <template #card-header>
          <h1>图片验证码</h1>
        </template>
        <template #form-items>
          <el-form-item label="验证码" prop="inputCode">
            <el-input
              v-model.trim="formData.inputCode"
              placeholder="输入验证码，不区分大小写"
              clearable
            ></el-input>
          </el-form-item>
        </template>
        <template #form-extra>
          <div class="captcha-container">
            <img :src="captchaUrl" @click="refreshCaptcha" alt="验证码" />
            <el-text>点击图片刷新验证码</el-text>
          </div>
        </template>
      </BaseCard>
    </el-dialog>
  </article>
</template>

<script setup>
import { ref, computed } from 'vue'
import { verifyCaptcha } from '@/api/captcha'
import BaseCard from './BaseCard.vue'
import { ElMessageBox } from 'element-plus'

const showCaptcha = defineModel()
const emit = defineEmits(['verified'])

const baseURL = ref('http://localhost:3001/api') // 后端 API 地址
const formData = ref({
  inputCode: '',
})
const formRules = ref({
  inputCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
})
const tiplinkText = ref('取消验证')
const cardShadow = ref('never')

const time = ref(Date.now())

const captchaUrl = computed(() => `${baseURL.value}/captcha?t=${time.value}`) // 添加时间戳避免缓存

// 刷新验证码
const refreshCaptcha = () => {
  time.value = Date.now()
}

// 提交验证码
const submitCaptcha = async () => {
  try {
    const { success, message } = await verifyCaptcha(formData.value.inputCode)
    ElMessageBox.confirm(`${message}`, {
      confirmButtonText: success ? '继续' : '重试',
      cancelButtonText: '取消',
      type: success ? 'success' : 'error',
      callback: (action) => {
        if (action === 'confirm') {
          if (success) emit('verified')
        } else refreshCaptcha()
      },
    })
    if (!success) refreshCaptcha()
  } catch {
    ElMessageBox.alert('验证码验证失败', {
      confirmButtonText: '确定',
      type: 'warning',
    })
    refreshCaptcha()
  }
}

// 初始加载验证码
refreshCaptcha()
</script>

<style lang="scss" scoped>
.image-captcha {
  :deep(.el-dialog) {
    width: 22rem;
    height: auto;
    .image-captcha-card {
      .el-card {
        border: none;
      }
      h1 {
        text-align: center;
        font-size: 1.2rem;
      }
      .captcha-container {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 0.2rem;
        margin-top: 1rem;
        img {
          width: 80%;
        }
      }
    }
  }
}
</style>
